package org.winexpress

import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.JSONObject
import org.codehaus.groovy.grails.web.json.JSONArray

class PaymentController {

    def  getTotalPrice =
    {
        def username= params['username']

        println username
        Customer user = Customer.findByUsername(username)
        def carts = user.shoppingCarts.toList()
        def cart = carts[0]
        JSONObject obj = new JSONObject()
        
        double totalprice=0.0
        def products =""
        cart.cartItems.each()
        {
            double price =  it.product.sellingPrice * it.quantity
            
            totalprice = totalprice+price
           
                products = products +it.product.productName + "," + it.product.sellingPrice  + "," + it.quantity+ ";"
           
        }
        products = products.substring(0,products.length()-1)  

        obj.put("totalprice", totalprice)
        obj.put("products",products)
        
        render obj as JSON
    }
    def success = 
    {
        def username =params ['username']
        Customer c= Customer.findByUsername(username)
        def addressDate = params['address']
        def addressDateList= addressDate.split('_')
        def address = addressDateList[0]
        def deliverdate = addressDateList[1]
        def amt = params['amt']
        Invoice i = new  Invoice()
        i.deliveryAddress =address
        i.deliveryDate = Date.parse('yyyy-M-d', deliverdate )
        Payment p = new Payment()
        p.amount = Double.parseDouble(amt)

        i.customer =c
      
        def carts = c.shoppingCarts.toList()
        def cart = carts[0]
        JSONObject obj = new JSONObject()
       i.save(flush: true)
        cart.cartItems.each()
        {
         //   double price =  it.products.sellingPrice * it.quantity
            InvoiceItem item = new InvoiceItem ()
            item.qty = it.quantity
             item.product  = it.product             
             Product product = Product.findById(it.products.id)
             product.stockCount = product.stockCount-it.quantity 
             print product.stockCount 
              i.addToInvoiceItem(item)
               item.save()
               product.save(flush:true)
          it.delete()     
            //totalprice = totalprice+price
        }
c.shoppingCarts.each()
{
    it.delete()
}
        //cart.delete()
        p.setInvoice(i)               
        p.save()
        obj.put("status","ok")
        render obj as JSON
    }
    
//    /*** This method set payment details for paypal ***/
//    def payByPaypal = 
//    {
//        def totalamount = params.hidepay
//        def receiver = params.receiver
//        def address = params.address
//        def opt = params.deliveryopt
//        BigDecimal amt = new BigDecimal(totalamount)
//        def items=""
//        
//	//delivery charges
//        if (opt == 'Registered postage')
//        {       
//            amt = amt +2.15
//        }
//        else if (opt == 'Self collection')
//        {
//            address ="1 Raffles Place 12-11"
//        }
//        
//        def strUsername = "game_1315666596_biz_api1.hotmail.com"
//        def strPassword = "1315666634"
//        def strSignature = "Ah8Lwovf8-hHc.RUGsR5KaCq7OH0A.c17KY4FoDbDT.0G89ajwnpqkjI"
//        def strAPIVersion = "65.1"
//        def strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature+"&VERSION="+strAPIVersion         
//        def strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";       
//        def user = session.userId +","+amt + "," + receiver + "," + address + "," + opt 
//        
//        //go to this url if user complets payment
//        def successUrl =ConfigurationHolder.config.grails.serverURL+ 'success?userid='+user             
//        //go to this url if user cancel payment halfway 
//        def cancelUrl = ConfigurationHolder.config.grails.serverURL +'cart/?userid='+user        
//        def strNVP = strCredentials + "&METHOD=SetExpressCheckout&RETURNURL="+successUrl+"&CANCELURL="+cancelUrl
//        strNVP = strNVP+"&PAYMENTREQUEST_0_PAYMENTACTION=SALE&PAYMENTREQUEST_0_CURRENCYCODE=SGD&PAYMENTREQUEST_0_AMT="+amt         
//        strNVP = strNVP+"&L_PAYMENTREQUEST_0_ITEMCATEGORY0=Digital"        
//        
//        
//        def customerId = session.customerId
//        Customer c = Customer.findById(customerId)
////        def carts = u.cartItems.toList()
//        def cartItems = c.shoppingCart.cartItems.toList()
//        def i = 0
//        //loop all items in shopping cart so will display on paypal
//        for (item in cartItems)
//        {
//            def qty = item.quantity
//            def p = item.products.toList()[0]
//            BigDecimal price = p.rentPrice
//            price = price.setScale(2)
//            if (i==0)
//            {
//                items = "&L_PAYMENTREQUEST_0_NAME"+i +"="+p.title + "&L_PAYMENTREQUEST_0_QTY"+ i +"="+ qty +"&L_PAYMENTREQUEST_0_AMT" +i+"="+price
//            }
//            else
//            {
//                items = items +"&L_PAYMENTREQUEST_0_NAME"+i +"="+p.title + "&L_PAYMENTREQUEST_0_QTY"+ i+"=" + qty  +"&L_PAYMENTREQUEST_0_AMT" +i+"="+price
//            }
//            i=i+1
//        }        
//        
//        strNVP = strNVP+items
//        //if delivery is registed package charge 2.15
//        if (opt == 'Registered postage')
//        {       
//            strNVP = strNVP +"&L_PAYMENTREQUEST_0_NAME"+i +"=postage&L_PAYMENTREQUEST_0_QTY"+ i+"=1&L_PAYMENTREQUEST_0_AMT" +i+"=2.15"
//            
//        }  
//        HttpClient httpclient = new DefaultHttpClient()
//        HttpResponse response
//        HttpPost httppost = new HttpPost(strNVPSandboxServer)
//        StringEntity se = new StringEntity(strNVP)
//        httppost.setEntity(se);          
//        response = httpclient.execute(httppost);
//        if (response != null) {            
//            HttpEntity r_entity = response.getEntity()
//            String res = EntityUtils.toString(r_entity)
//            def arr  = res.split("=")
//            arr = arr[1].split('&')
//            def token = "EC-" + arr[0].toString().substring(5)
//            def checkoutUrl = "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=" + token
//            redirect(url:checkoutUrl)
//        }
//    }
//    /*** End this method set payment details for paypal ***/
//    
//        
//    /*** This method is called to update payment status and create invoice ***/    
//    def success = 
//    {
//        def token = params.token
//        Map map = [:]        
//        Calendar dueDate = Calendar.getInstance()
//        dueDate.add(Calendar.DATE,14)        
//        String DATE_FORMAT = "yyyy-MM-dd";
//        SimpleDateFormat sdf =new SimpleDateFormat(DATE_FORMAT);        
//        def due = sdf.format(dueDate.getTime())
//        def strUsername = "game_1315666596_biz_api1.hotmail.com"
//        def strPassword = "1315666634"
//        def strSignature = "Ah8Lwovf8-hHc.RUGsR5KaCq7OH0A.c17KY4FoDbDT.0G89ajwnpqkjI"
//        def strCredentials = "USER=" + strUsername + "&PWD=" + strPassword + "&SIGNATURE=" + strSignature
//        def strNVPSandboxServer = "https://api-3t.sandbox.paypal.com/nvp";
//        def strAPIVersion = "56.0";
//        def strNVP = strCredentials + "&METHOD=GetExpressCheckoutDetails&TOKEN="+token+"&VERSION=" + strAPIVersion
//        HttpClient httpclient = new DefaultHttpClient()
//        HttpResponse response
//        HttpPost httppost = new HttpPost(strNVPSandboxServer)
//        StringEntity se = new StringEntity(strNVP)        
//        httppost.setEntity(se);          
//        response = httpclient.execute(httppost);
//        if (response != null) {
//            HttpEntity r_entity = response.getEntity()
//            String res = EntityUtils.toString(r_entity)
//            def arr = res.split("&")
//            String ack = arr[3].substring(4)
//            if (ack == "Success")
//            {
//                token = arr[0].toString().substring(6)
//                def payeeID = arr[7].toString().substring(8)                
//                def userid = params.userid                 
//                def args = userid.split(',')
//                userid = args[0].toString()
//                def amount = Double.parseDouble(args[1])
//                strNVP = strCredentials+"&METHOD=DoExpressCheckoutPayment&=PAYMENTREQUEST_0_PAYMENTACTION=Authorization&TOKEN="+token+"&PAYERID="+payeeID+"&PAYMENTREQUEST_0_CURRENCYCODE=SGD&PAYMENTREQUEST_0_AMT="+amount + "&VERSION=" + 65.1
//                httpclient = new DefaultHttpClient()
//                httppost = new HttpPost(strNVPSandboxServer)
//                se = new StringEntity(strNVP)        
//                httppost.setEntity(se);          
//                response = httpclient.execute(httppost);
//                if (response != null) {
//                    r_entity = response.getEntity()
//                    res = EntityUtils.toString(r_entity)
//                    def arrs =res.split("&")
//                    ack= arrs[4].toString().substring(4)
//                    if (ack=="Success")
//                    {
//                        def receiver =args[2].toString()
//                        def address = args[3].toString()
//                        def opt = args[4].toString()
//                        Users user = Users.findById(userid)
//                        session.userId= user.id
//                        def email =  user.userDetails.email
//                        def fullName = user.userDetails.fullName
//                        def carts = user.cartItems.toList()                
//                        Calendar deliveryDate = Calendar.getInstance()
//                        deliveryDate.add(Calendar.DATE, 1)
//                        Date payDate = new Date()
//                        int fromYear = payDate.getYear() + 1900
//                        int fromMonth = payDate.getMonth() + 1
//                        String tempPayDate = fromYear + "-" + fromMonth+ "-" + payDate.getDate()
//                        payDate = Date.parse('yyyy-M-dd', tempPayDate)
//
//                        Invoices i = new Invoices()
//                        i.setDueDate(dueDate.getTime())       
//                        i.setDateTime(payDate)
//                        i.setDeliveryLocation(address)
//                        i.setDeliveryDateTime(deliveryDate.getTime())
//                        i.setDeliveryType(opt)
//                        i.setDeliveryStatus("Processing")
//                        i.setStatus("Open")
//                        i.setReceiverName(receiver)              
//                        user.addToInvoices(i)          
//                        for (c in carts)
//                        {
//                            def cart = CartItems.findAllById(c.id)[0]
//                            user.removeFromCartItems(cart)
//                            Products p =  cart.products.toList()[0]
//                            int current =  p.salesCount +1
//                            p.salesCount = current
//                            int qty = cart.quantity
//                            int count = 0
//                            map[p.title] = qty
//                            p.serials.each
//                            {
//                        
//                                Serials Serial = it
//                                String name = Serial.status
//                                if (name.equals("A") == true)
//                                {
//                                    if (count <qty)
//                                    {
//                                        Serial.status ="R"
//                                        count = count + 1
//                                        InvoiceItems item = new InvoiceItems()                              
//                                        i.addToInvoiceItems(item)
//                                        Serial.addToInvoiceItems(item)                             
//                                        item.save()
//                                        Serial.save()
//                                    }
//                                }
//                            }                
//                            def tmp=[]
//                            cart.products.each { tmp << it }
//                            tmp.each {
//                                cart.removeFromProducts(it) 
//                            }
//                            cart.delete()                                                         
//                        }
//                        Payments pay = new Payments()
//                        pay.setAmount(amount)
//                        pay.setDateTime(payDate)
//                        pay.setInvoices(i)               
//                        pay.save()
//                        session.setAttribute("cartAmt",null)
//
//                        //Send email                        
//                        AppEmailManager emailManager = new AppEmailManager()
//                        String emailResult = emailManager.emailPaymentSuccess(email,fullName)                    
//                        
//                    }
//                }                
//                flash.message = "Thank you for the payment. An invoice has been created for you."                        
//                redirect(controller:'transactionHistory', action: 'view')                
//                      
//            }
//            else
//            {
//               flash.error = "Sorry, Paypal Sandbox has encountered an error."    
//               redirect(controller:'cart', action: 'viewCart')      
//            }
//
//            
//        }
//        [map:map,dueDate:due]
//    }
//    /*** This method is called to update payment status and create invoice ***/ 
}
